//
//  QYOrderDetailVC.m
//  QingYue
//
//  Created by Zheng on 2019/3/26.
//  Copyright © 2019 com.lanou.product_A. All rights reserved.
//

#import "QYOrderDetailVC.h"
#import "QYOrderDetailBookCell.h"
#import "CZHLogisticCell.h"
#import "CZHGlobalHeader.h"
#import "QYOrderDetailModel.h"

@interface QYOrderDetailVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UIButton *mobileBtn;
@property (nonatomic, strong) NSMutableArray *logisticArray;

@property (nonatomic, strong) QYOrderDetailModel *detailModel;


@end

@implementation QYOrderDetailVC

- (NSMutableArray *)logisticArray {
    if (!_logisticArray) {
        _logisticArray = [NSMutableArray array];
    }
    return _logisticArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    
    [self.listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
    }];
    
    [self czh_getData];
    
    [self loadData];
}


- (void)loadData {
    
    if (![_model.RrackingNumber isKindOfClass:[NSNull class]]) {
        NSDictionary *param = @{@"RrackingNumber":_model.RrackingNumber};
        [[YCRequestDataService sharedManager] Post:@"GetOrderDetailsByRN" parameters:param success:^(id response) {
            if ([response[@"Code"] isEqualToString:@"成功"]) {
                
                _detailModel = [[QYOrderDetailModel alloc] initWithDataDic:response[@"res"]];
                _detailModel.logisticModel = [[QYOrderDetailModel alloc] initWithDataDic:_detailModel.RrackingInfo.mj_JSONObject];
                
                NSArray *list = _detailModel.RrackingInfo.mj_JSONObject[@"Traces"];
                
                
                [self.logisticArray removeAllObjects];
                
                for (NSInteger i = 0; i < list.count; i++) {
                    
                    NSDictionary *dic = @{@"time":list[i][@"AcceptTime"],
                                          @"content":list[i][@"AcceptStation"]};

                    CZHLogisticFrameModel *frameModel = [[CZHLogisticFrameModel alloc] init];
                    CZHLogisticModel *model = [CZHLogisticModel czh_parse:dic];
                    model.indexCount = i;
                    model.totalCount = list.count;
                    frameModel.model = model;
                    [self.logisticArray addObject:frameModel];
                    
                }
                
                [_listTableView reloadData];
            }
            
        } failure:^{
            kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
            
        }];
    }
    

}

- (void)czh_getData {
    
    
//    NSDictionary *first = @{@"time":@"2018-03-07 14:03:53", @"content":@"[黄石市]快件已在黄石签收 签收人：XXXX,感谢您使用XX快递，期待再次为您服务!哈哈哈哈哈[15912345678]"};
//    NSDictionary *second = @{@"time":@"2018-03-07 10:00:00", @"content":@"[黄石市]派件员XXX[0714-5381795]正在派件傻哈哈傻哈哈"};
//    NSDictionary *third = @{@"time":@"2018-03-07 8:00:00", @"content":@"[黄石市]快件已到达黄石"};
//    NSDictionary *fourth = @{@"time":@"2018-03-06 8:00:00", @"content":@"[武汉市]快件离开武汉中转部已发往黄石"};
//    NSDictionary *fifth = @{@"time":@"2018-03-06 5:00:00", @"content":@"[武汉市]快件已到达武汉中转部"};
//    NSDictionary *sixth = @{@"time":@"2018-03-06 1:00:00", @"content":@"[深圳市]快件已离开深圳发往武汉中转部"};
//    NSDictionary *seventh = @{@"time":@"2018-03-05 19:00:00", @"content":@"[深圳市]XXX已收件[13986600772]"};
//    NSDictionary *eighth = @{@"time":@"2018-03-05 17:00:00", @"content":@"您的订单由第三方卖家拣货完毕，正通知快递公司揽件中"};
//    NSDictionary *ninth = @{@"time":@"2018-03-05 13:00:00", @"content":@"您提交了订单，请等待第三方卖家系统确认[15988888888]"};
//
//    NSArray *array = @[first, second, third, fourth, fifth, sixth, seventh, eighth, ninth];
//
//    NSInteger totalCount = array.count;
    

    

}


#pragma mark - 布局
#pragma mark - lazy load
- (UITableView *)listTableView
{
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.separatorColor = UIColorFromRGB(0xe3e3e3);
        _listTableView.estimatedSectionFooterHeight = 0.0f;
        _listTableView.estimatedSectionHeaderHeight = 0.0f;
        _listTableView.rowHeight = 130;
        _listTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _listTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        
        if (@available(iOS 11.0, *)) {
            _listTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        [_listTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"kCellID"];
        [_listTableView registerClass:[QYOrderDetailBookCell class] forCellReuseIdentifier:@"kCellID1"];
        
        [self.view addSubview:_listTableView];
    }
    return _listTableView;
}

- (UIButton *)mobileBtn {
    if (!_mobileBtn) {
        _mobileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_mobileBtn setTitle:@"拨打" forState:UIControlStateNormal];
        _mobileBtn.titleLabel.font = [UIFont systemFontOfSize:9];
        _mobileBtn.layer.cornerRadius = 7.5;
        _mobileBtn.layer.masksToBounds = YES;
        _mobileBtn.layer.borderWidth = 1;
        [_mobileBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _mobileBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [_mobileBtn addTarget:self action:@selector(mobileBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _mobileBtn;
}


#pragma mark - tableview delegate and dataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        QYOrderDetailBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCellID1" forIndexPath:indexPath];
        if (_detailModel) {
            [cell.bookImgv sd_setImageWithURL:[NSURL URLWithString:_detailModel.BookPic] placeholderImage:[UIImage imageNamed:@"图书占位.jpg"]];
            cell.bookNameLbl.text = _detailModel.BookName;
            cell.statusLbl.text = [self getStateStr];

        } else {
            [cell.bookImgv sd_setImageWithURL:[NSURL URLWithString:_model.BookPic] placeholderImage:[UIImage imageNamed:@"图书占位.jpg"]];
            cell.bookNameLbl.text = _model.BookName;
        }
        
        if ([_model.RrackingNumber isKindOfClass:[NSNull class]]) {
            cell.statusLbl.text = @"暂无物流";
        }

        return cell;
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCellID" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:12];

        NSArray *titlesArr;
        
        if (_detailModel) {
            titlesArr = @[[NSString stringWithFormat:@"快递编号：%@",_detailModel.logisticModel.LogisticCode],
                          [NSString stringWithFormat:@"快递公司：%@",[self getPostName]]];
        }
        else
        {
            titlesArr = @[@"快递编号：",@"快递公司："];
        }
        
        cell.textLabel.text = titlesArr[indexPath.row];
        
        
        if (indexPath.row == 2) {
            [_mobileBtn removeFromSuperview];
            [cell.contentView addSubview:self.mobileBtn];
            [_mobileBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(90);
                make.width.mas_equalTo(50);
                make.height.mas_equalTo(15);
                make.centerY.offset(0);
            }];
        }
        
        
        return cell;
    } else if (indexPath.section == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCellID" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:12];

        NSArray *titlesArr = @[@"申请记录编号：",@"申请记录时间："];
        if (_detailModel) {
            titlesArr = @[[NSString stringWithFormat:@"申请记录编号：%@",_detailModel.RecordNumber],
                          [NSString stringWithFormat:@"申请记录时间：%@",_detailModel.CreateTime]];
        }
        else
        {
            titlesArr = @[[NSString stringWithFormat:@"申请记录编号：%@",_model.RecordNumber],
                          [NSString stringWithFormat:@"申请记录时间：%@",_model.CreateTime]];
        }

        cell.textLabel.text = titlesArr[indexPath.row];
        return cell;
    } else {
        CZHLogisticCell *cell = [CZHLogisticCell czh_cellWithTableView:tableView];
        
        cell.frameModel = self.logisticArray[indexPath.row];
        
        return cell;

    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    } else if (section == 2) {
        return 2;
    } else {
        return self.logisticArray.count;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 1;
    }
    return 10.;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 50;
    } else if (indexPath.section == 1 || indexPath.section == 2) {
        return 30;
    } else {
        CZHLogisticFrameModel *frameModel = self.logisticArray[indexPath.row];
        return frameModel.cellHeight;
    }
}

- (void)mobileBtnAction {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"13464567799"]]];
}

- (NSString *)getStateStr {
    
    NSInteger state = _detailModel.logisticModel.State.integerValue;
    NSString *stateStr = @"";
    switch (state) {
        case 0:
            stateStr = @"无轨迹";
            break;
        case 1:
            stateStr = @"已揽收";
            break;
        case 2:
            stateStr = @"在途中";
            break;
        case 3:
            stateStr = @"已签收";
            break;
        case 4:
            stateStr = @"问题件";
            break;

        default:
            break;
    }
    
    return stateStr;
}

- (NSString *)getPostName {
    NSString *codeStr = _detailModel.logisticModel.ShipperCode;
    
    NSDictionary *param = @{@"HTKY":@"百世快递",
                            @"ZTO":@"中通快递",
                            @"STO":@"申通快递",
                            @"YTO":@"圆通速递",
                            @"YD":@"韵达速递",
                            @"YZPY":@"邮政快递包裹",
                            @"EMS":@"EMS",
                            @"HHTT":@"天天快递",
                            @"JD":@"京东快递",
                            @"UC":@"优速快递",
                            @"DBL":@"德邦快递",
                            @"ZJS":@"宅急送",
                            @"TNT":@"TNT快递",
                            @"UPS":@"UPS",
                            @"DHL":@"DHL",
                            @"FEDEX":@"FEDEX联邦(国内件）",
                            @"FEDEX_GJ":@"FEDEX联邦(国际件）",
                          };
    
    return param[codeStr];
}


@end
